<template>
  <div class="order-list">
    <el-form :inline="true" :model="formInline" class="demo-form-inline" size="mini">
      <el-form-item label="手机">
        <el-input v-model="formInline.telPhone" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="订单ID">
        <el-input v-model="formInline.orderCode" placeholder="订单ID"></el-input>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="formInline.name" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item label="下单时间" class="order-time">
        <el-row>
          <el-col :span="11" class="time-width">
            <el-date-picker
              v-model="formInline.startTime"
              type="datetime"
              placeholder="选择日期时间"
              default-time="00:00:00">
            </el-date-picker>
          </el-col>
          <el-col :span="1" class="time-span">~</el-col>
          <el-col :span="11" class="time-width">
            <el-date-picker
              v-model="formInline.endTime"
              type="datetime"
              placeholder="选择日期时间"
              default-time="23:59:59">
            </el-date-picker>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="支付状态">
        <el-select clearable v-model="formInline.status" placeholder="请选择支付状态">
          <el-option v-for="(item, index) in orderStatus"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">下载</el-button>
      </el-form-item>
    </el-form>
    <el-checkbox-group v-model="checkList" @change="changeSelection()">
      <el-checkbox label="1">订单ID</el-checkbox>
      <el-checkbox label="2">产品名称</el-checkbox>
      <el-checkbox label="3">购买数量</el-checkbox>
      <el-checkbox label="5">可激活数量</el-checkbox>
      <el-checkbox label="4">已激活数量</el-checkbox>
      <el-checkbox label="6">失效数量</el-checkbox>
      <el-checkbox label="7">申请退单数量</el-checkbox>
      <el-checkbox label="8">已退单数量</el-checkbox>
      <el-checkbox label="9">手机号码</el-checkbox>
      <el-checkbox label="10">客人姓名</el-checkbox>
      <!--<el-checkbox label="11">代理商</el-checkbox>-->
      <el-checkbox label="12">单价</el-checkbox>
      <el-checkbox label="13">总价</el-checkbox>
      <el-checkbox label="14">单返佣</el-checkbox>
      <el-checkbox label="15">总返佣</el-checkbox>
      <!--<el-checkbox label="16">激活码</el-checkbox>-->
      <el-checkbox label="16">下单时间</el-checkbox>
      <!--<el-checkbox label="">激活人姓名</el-checkbox>-->
      <!--<el-checkbox label="">申请退单时间</el-checkbox>-->
      <!--<el-checkbox label="">激活时间</el-checkbox>-->
      <!--<el-checkbox label="">退单时间</el-checkbox>-->
      <!--<el-checkbox label="17">微信账号</el-checkbox>-->
      <!--<el-checkbox label="18">支付方式</el-checkbox>-->
    </el-checkbox-group>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border highlight-current-row size="mini" v-if="isUpdateTable">
      <el-table-column align="center" label='订单ID' width="136" v-if="isShowOrderId"  prop="orderCode">
        <el-table-column label="支付状态" width="136" align="center" prop="statusStr">
          <template slot-scope="scope">
            <div>{{scope.row.orderCode}}</div>
            <div class="txt-align" :class="typeClassMap[scope.row.status]">{{scope.row.statusStr}}</div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="产品名称" v-if="isShowPrdName" prop="productName" width="80" align="center"></el-table-column>
      <el-table-column label="总数" min-width="60" align="center"  prop="num" v-if="num"></el-table-column>
      <el-table-column label="可激活" min-width="60" align="center" v-if="unActiveNum"  prop="orderCountDto.unActiveNum">
        <el-table-column label="已激活" min-width="60" align="center" v-if="activeNum"  prop="orderCountDto.activeNum">
          <template slot-scope="scope">
            <div>{{scope.row.orderCountDto.unActiveNum}}</div>
            <div>{{scope.row.orderCountDto.activeNum}}</div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="已激活" min-width="60" align="center" v-if="!unActiveNum && activeNum" prop="orderCountDto.activeNum"></el-table-column>
      <el-table-column label="已失效" min-width="60" align="center" v-if="overDueNum" prop="orderCountDto.overDueNum"></el-table-column>
      <el-table-column label="申请退单" min-width="60" align="center" v-if="refundingNum" prop="orderCountDto.refundingNum">
        <el-table-column label="已退单" min-width="60" align="center" v-if="refundedNum" prop="orderCountDto.refundedNum">
          <template slot-scope="scope">
            <div>{{scope.row.orderCountDto.refundingNum}}</div>
            <div>{{scope.row.orderCountDto.refundedNum}}</div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="已退单" min-width="60" align="center" v-if="!refundingNum && refundedNum" prop="orderCountDto.refundedNum"></el-table-column>
      <el-table-column label="手机号码" width="100" align="center" v-if="telphone" prop="telphone"></el-table-column>
      <el-table-column label="客人姓名" width="80" align="center" v-if="name" prop="name"></el-table-column>
      <!--<el-table-column label="代理商" min-width="100" align="center" v-if="orgName" prop="orgName"></el-table-column>-->
      <!--<el-table-column label="微信账号" min-width="100" align="center" v-if="nickName" prop="nickName"></el-table-column>-->
      <el-table-column label="单价（元）" min-width="80" align="center" v-if="unitAmountFormat" prop="unitAmountFormat">
        <el-table-column label="总价（元）" min-width="80" align="center" v-if="orderAmountFormat" prop="orderAmountFormat">
          <template slot-scope="scope">
            <div>{{scope.row.unitAmountFormat}}</div>
            <div>{{scope.row.orderAmountFormat}}</div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="总价（元）" min-width="80" align="center" v-if="!unitAmountFormat && orderAmountFormat" prop="orderAmountFormat"></el-table-column>
      <el-table-column label="单返佣（元）" min-width="80" align="center" v-if="serviceCharge" prop="serviceCharge">
        <el-table-column label="总返佣（元）" min-width="80" align="center" v-if="serviceChargeTotal" prop="serviceChargeTotal">
          <template slot-scope="scope">
            <div>{{scope.row.serviceCharge}}</div>
            <div>{{scope.row.serviceChargeTotal}}</div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="总返佣（元）" min-width="80" align="center" v-if="!serviceCharge && serviceChargeTotal" prop="serviceChargeTotal"></el-table-column>
      <!--<el-table-column label="支付方式" width="80" align="center" v-if="payTypeStr" prop="payTypeStr"></el-table-column>-->
      <el-table-column label="下单时间" width="80" align="center" v-if="cTStr" prop="cTStr">
        <template slot-scope="scope">
          <div v-html="scope.row.cTStr"></div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="60" align="center" v-if="checkList.length >0">
        <template slot-scope="scope">
          <div class="dropdown">
            <a href="javascript:void(0);" class="dropdown-btn"></a>
            <div class="dropdown-content">
              <a href="javascript:void(0);" @click="openRefundDialog(scope.row.orderId)" v-if="(scope.row.status!=9 && scope.row.status!=1)">申请退单</a>
              <a href="javascript:void(0);" @click="checkOrderDetail(scope.row.orderId)">查看详情</a>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!--申请退单-->
    <el-dialog
      title="申请退单"
      width="500px"
      :visible.sync="refundDialogVisible"
      @close="resetForm('refundForm')">
      <el-form label-width="100px" :inline="false" :model="refundForm" ref="refundForm" :rules="refundFormRules" class="demo-form-inline" size="small">
        <el-form-item label="退单数量" prop="refundNum">
          <el-input v-model="refundForm.refundNum" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="退单金额">
          <el-input v-model="refundAccount" placeholder="" disabled=""></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="refundDialogVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="submitRefund('refundForm')" size="small" :disabled="isSend">确 定</el-button>
            </span>
    </el-dialog>
    <!--查看详情弹窗-->
    <el-dialog
      title="订单详情"
      width="800px"
      :visible.sync="detailDialogVisible">
      <el-button type="primary" size="mini" @click="checkActivedCode(orderInfo.orderId)">查看激活码</el-button>
      <p class="p">
        <span class="span">产品名称：<span>{{orderInfo.productName}}</span></span>
        <span class="span">下单时间：<span>{{orderInfo.cTStr}}</span></span>
        <!--<span class="span">代理商名称：<span>{{orderInfo.orgName}}</span></span>-->
      </p>
      <p class="p">
        <span class="span">购买数量：<span>{{orderInfo.num}}</span></span>
        <span class="span">单返佣：<span>{{orderInfo.serviceCharge}}元</span></span>
        <span class="span">总返佣：<span>{{orderInfo.serviceChargeTotal}}元</span></span>
      </p>
      <p class="p">
        <span class="span">单价：<span>{{orderInfo.unitAmount}}元</span></span>
        <span class="span">总价：<span>{{orderInfo.orderAmount}}元</span></span>
      </p>
      <p class="p">
        <span class="span">客人姓名：<span>{{orderInfo.name}}</span></span>
        <!--<span class="span">微信账号：<span>{{orderInfo.nickName}}</span></span>-->
        <span class="span">手机号：<span>{{orderInfo.telPhone}}</span></span>
      </p>
      <p class="p">
        <span class="span">已激活数量：<span v-if="orderInfo.orderCount">{{orderInfo.orderCount.activeNum}}</span></span>
        <span class="span">已失效数量：<span v-if="orderInfo.orderCount">{{orderInfo.orderCount.overDueNum}}</span></span>
        <span class="span">可激活数量：<span v-if="orderInfo.orderCount">{{orderInfo.orderCount.unActiveNum}}</span></span>
      </p>
      <el-table
        :data="orderInfo.activeList"
        size="mini"
        border
        style="width: 100%"
        v-if="orderInfo.activeList&&orderInfo.activeList.length">
        <el-table-column
          prop="name"
          label="已激活会员姓名"
          align="center">
        </el-table-column>
        <el-table-column
          prop="cardCode"
          label="会员ID"
          align="center">
        </el-table-column>
        <el-table-column
          prop="activeCode"
          label="激活码"
          align="center"
          width="">
        </el-table-column>
        <el-table-column
          prop="idCard"
          class="stock"
          label="身份证号"
          align="center">
        </el-table-column>
        <el-table-column
          prop="activeTimeStr"
          label="激活时间"
          align="center">
        </el-table-column>
      </el-table>
      <el-table
        :data="orderInfo.refundingList"
        size="mini"
        border
        style="width: 100%"
        v-if="orderInfo.refundingList&&orderInfo.refundingList.length">
        <el-table-column
          prop="num"
          label="申请退单数量"
          align="center">
        </el-table-column>
        <el-table-column
          prop="applyUser"
          label="申请人"
          align="center"
          width="">
        </el-table-column>
        <el-table-column
          prop="refundTimeStr"
          class="stock"
          label="申请退单时间"
          align="center">
        </el-table-column>
      </el-table>
      <el-table
        :data="orderInfo.refundedList"
        size="mini"
        border
        style="width: 100%"
        v-if="orderInfo.refundedList&&orderInfo.refundedList.length">
        <el-table-column
          prop="num"
          label="已退单数量"
          align="center">
        </el-table-column>
        <el-table-column
          prop="verifyUser"
          label="操作人"
          align="center"
          width="">
        </el-table-column>
        <el-table-column
          prop="refundTimeStr"
          class="stock"
          label="退单时间"
          align="center">
        </el-table-column>
      </el-table>
      <!--内层激活码弹窗-->
      <el-dialog
        width="30%"
        title="激活码"
        :visible.sync="innerVisible"
        append-to-body>
        <el-table
          :data="activedCodeList"
          size="mini"
          border
          style="width: 100%">
          <el-table-column
            prop="code"
            label="激活码码号"
            align="center">
          </el-table-column>
          <el-table-column
            prop="activeTimeStr"
            label="激活时间"
            align="center"
            width="">
          </el-table-column>
          <el-table-column
            prop="loseTimeStr"
            class="stock"
            label="过期时间"
            align="center">
          </el-table-column>
          <el-table-column
            prop="statusStr"
            class="stock"
            label="状态"
            align="center">
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
                    <el-button size="small" @click="innerVisible = false">关 闭</el-button>
                </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="detailDialogVisible = false">关 闭</el-button>
            </span>
    </el-dialog>
    <el-pagination
      layout="total, prev, pager, next, jumper"
      :total="total"
      :page-size="20"
      :current-page="currentPage"
      @current-change="handleChangePage">
    </el-pagination>
  </div>
</template>
<script>
//  import { getOrderList, getOrderDetail, getOrderCode, getOrderStatus } from '@/api/orderList'
  import { getOrderList, getOrderDetail, getOrderCode, getOrderStatus, checkOrdersRefundNum, ordersRefund } from '@/api/dOrderList'
import { Message } from 'element-ui'
  export default {
    data() {
      // 退单数量校验
      let refundNumVali = (rule, value, callback) => {
        let reg = /^\d+$/
        if ((value < 1) && value) {
          callback(new Error('退单数不能小于1'))
          return
        } else if (!reg.test(value) && value) {
          callback(new Error('请输入整数'))
          return
        }
//        if (value > this.maxRefundNum) {
//          callback(new Error('退单数不能大于可激活数和已失效数之和' + this.maxRefundNum))
//          return
//        }
        callback()
      }
      return {
        isSend: false,
        list: [],
        listLoading: false,
        formInline: {
          telPhone: null,
          orderCode: null,
          name: null,
          startTime: null,
          endTime: null,
          status: null
        },
        isUpdateTable: true,
        checkList: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '12', '13', '14', '15', '16'],
        isShowOrderId: true,
        isShowPrdName: true,
        num: true,
        unActiveNum: true,
        activeNum: true,
        refundingNum: true,
        refundedNum: true,
        overDueNum: true,
        telphone: true,
        unitAmountFormat: true,
        orderAmountFormat: true,
        name: true,
        orgName: true,
        serviceCharge: true,
        serviceChargeTotal: true,
        cTStr: true,
        nickName: true,
        payTypeStr: true,
        total: null,
        currentPage: 1,
        pageSize: 20,
        typeClassMap: {
          1: 'not-pay',
          2: 'has-pay',
          9: 'has-cancel'
        },
        orderStatus: [],
        // 退单弹框
        refundDialogVisible: false,
        refundForm: {
          refundNum: null
        },
        refundFormId: null,
        refundAccount: null,
        refundFormRules: {
          refundNum: [
            { required: true, message: '请输入退单数量', trigger: 'blur' },
            { validator: refundNumVali }
          ]
        },
        // 订单详情弹框
        detailDialogVisible: false,
        orderInfo: {},
        activedCodeList: [],
        innerVisible: false
      }
    },
    created() {
      this.fetchData()
      this.getOrderStatus()
    },
    watch: {
      refundForm: {
        handler: function() {
//          this.$refs['refundForm'].validate((valid) => {
//            if (valid) {
//              let params = {
//                orderId: parseInt(this.refundFormId),
//                orderNum: parseInt(this.refundForm.refundNum)
//              }
//              this.refundForm.refundAccount = null
//              checkOrdersRefundNum(params).then(res => {
//                let data = res.data
//                if (data.errorCode === 'E_000') {
//                  this.refundForm.refundAccount = data.body.amount
//                }
//              })
//            }
//          })
          this.getRefundAccount('refundForm')
        },
        deep: true
      }
    },
    methods: {
      resetForm(formName) {
        this.$refs[formName].resetFields()
        this.refundForm.refundNum = null
        this.refundAccount = null
      },
      submitRefund(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.refundAccount) {
              let params = {
                orderId: parseInt(this.refundFormId),
                num: parseInt(this.refundForm.refundNum),
                refundAmount: this.refundAccount
              }
              this.isSend = true
              ordersRefund(params).then(res => {
                let data = res.data
                if (data.errorCode === 'E_000') {
                  this.refundDialogVisible = false
                  this.isSend = false
                  this.refundForm.refundNum = null
                  this.fetchData()
                  Message({
                    message: data.message,
                    type: 'success',
                    duration: 2 * 1000
                  })
                }
              })
            } else {
              Message({
                message: '退单金额不能为空',
                type: 'error',
                duration: 2 * 1000
              })
            }
          }
        })
      },
      openRefundDialog(orderId) {
        this.refundDialogVisible = true
        this.refundFormId = orderId
      },
      getRefundAccount(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let params = {
              orderId: parseInt(this.refundFormId),
              orderNum: parseInt(this.refundForm.refundNum)
            }
            this.refundAccount = null
            checkOrdersRefundNum(params).then(res => {
              let data = res.data
              if (data.errorCode === 'E_000') {
                this.refundAccount = data.body.amount
              }
            })
          } else {
            return false
          }
        })
      },
      fetchData() {
        this.listLoading = true
        let formInline = this.formInline
        let params = {
          telphone: formInline.telPhone || null,
          orderCode: formInline.orderCode || null,
          name: formInline.name || null,
          startTime: new Date(formInline.startTime).getTime() || null,
          endTime: new Date(formInline.endTime).getTime() || null,
          status: formInline.status || null,
          pageNumber: this.currentPage,
          pageSize: this.pageSize
        }
        getOrderList(params).then(res => {
          let data = res.data
          this.listLoading = false
          if (data.errorCode === 'E_000') {
            data.body.list.forEach(item => {
              item.cTStr = item.cTStr.replace(/\s+/, '<br>')
            })
            this.list = data.body.list
            this.total = data.body.total
          }
        }).catch(() => {
          this.listLoading = false
        })
      },
      changeSelection() {
        this.isShowOrderId = this.checkList.indexOf('1') > -1
        this.isShowPrdName = this.checkList.indexOf('2') > -1
        this.num = this.checkList.indexOf('3') > -1
        this.unActiveNum = this.checkList.indexOf('5') > -1
        this.activeNum = this.checkList.indexOf('4') > -1
        this.overDueNum = this.checkList.indexOf('6') > -1
        this.refundingNum = this.checkList.indexOf('7') > -1
        this.refundedNum = this.checkList.indexOf('8') > -1
        this.telphone = this.checkList.indexOf('9') > -1
        this.name = this.checkList.indexOf('10') > -1
        this.orgName = this.checkList.indexOf('11') > -1
        this.unitAmountFormat = this.checkList.indexOf('12') > -1
        this.orderAmountFormat = this.checkList.indexOf('13') > -1
        this.serviceCharge = this.checkList.indexOf('14') > -1
        this.serviceChargeTotal = this.checkList.indexOf('15') > -1
        this.cTStr = this.checkList.indexOf('16') > -1
        this.nickName = this.checkList.indexOf('17') > -1
        this.payTypeStr = this.checkList.indexOf('18') > -1

        // 刷新表格
        this.updateTable()
      },
      updateTable() {
        this.isUpdateTable = false
        this.$nextTick(() => {
          this.isUpdateTable = true
        })
      },
      onSearch() {
        this.currentPage = 1
        this.fetchData()
      },
      handleChangePage(val) {
        this.currentPage = val
        this.fetchData()
      },
      checkOrderDetail(orderId) {
        this.detailDialogVisible = true
//        let params = {
//          orderId: orderId
//        }
        getOrderDetail(orderId).then(res => {
          let data = res.data
          if (data.errorCode === 'E_000') {
            this.orderInfo = data.body
          }
        })
      },
      checkActivedCode(orderId) {
        this.innerVisible = true
        let params = {
          orderId: orderId
        }
        getOrderCode(params).then(res => {
          let data = res.data
          if (data.errorCode === 'E_000') {
            this.activedCodeList = data.body
          }
        })
      },
      getOrderStatus() {
        getOrderStatus().then(res => {
          let data = res.data
          if (data.errorCode === 'E_000') {
            this.orderStatus = data.body
          }
        })
      }
    }
  }
</script>
<style lang="scss">
  .order-list{
    .el-dialog__body{
      padding-top: 10px;
    }
    .el-table__header-wrapper{
      overflow: visible;
    }
    .order-time{
      .el-form-item__content{
        width: 480px;
      }
      .time-width{
        width: 220px;
      }
      .time-span{
        text-align: center;
      }
    }
    .el-table{
      /*margin-top: 0px;*/
      overflow: visible !important;
    }
    .el-table .el-table__body-wrapper {
      overflow: visible;
    }
    .el-table .cell {
      padding: 0 4px;
      overflow: visible;
    }
  }
</style>
<style lang="scss" scoped>
  .span{
    display: inline-block;
    width: 32%;
    text-align: left;
    vertical-align: top;
    >span{
      color: #90949c;
      word-wrap: break-word;
      word-break: break-all;
    }
  }
  .txt-align{
    text-align: right;
  }
  .not-pay{
    color: #fb9150;
  }
  .has-pay{
    color: #5ec62a;
  }
  .has-cancel{
    color: #3399ff;
  }
</style>
